package com.mreko.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.mreko.pojo.ChatBean;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class ChatThread implements Runnable {
	private Handler handler;
	// 用于处理发送消息的handler 接受用户输入的消息
	public Handler sendHandler;

	private String ip;
	private int port;
	private Socket s;
	ObjectInputStream ois;
	ObjectOutputStream oos;

	public ChatThread(Handler handler, String ip, int port, Context context) {
		this.handler = handler;
		this.ip = ip;
		this.port = port;
	}

	public void run() {
		System.out.println("进入了Run");
		try {
			s = new Socket(ip, port);
			System.out.println("if is Close?" + s.isClosed());
			System.out.println("if is Connect?" + s.isConnected());
			System.out.println("if is isInputShutdown?" + s.isInputShutdown());
			ois = new ObjectInputStream(s.getInputStream());
			oos = new ObjectOutputStream(s.getOutputStream());
			System.out.println("ois:" + ois.available());
			// 启动一条子线程来读取服务器响应的数据
			new Thread() {
				public void run() {
					ChatBean chatBean = null;
					// 不断读取socket输入流中的内容
					try {
						while ((chatBean = (ChatBean) ois.readObject()) != null) {
							// 每当读到来自服务器的数据之后，发送消息通知程序
							// 界面显示该消息
							Message msg = new Message();
							msg.what = 0x123;
							msg.obj = chatBean;
							handler.sendMessage(msg);
							System.out.println("Send Message to UI handler!");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();

		} catch (Exception e) {
			e.printStackTrace();
		}

		// 启动发送消息的handler用于向服务器发送消息
		Looper.prepare();
		sendHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				try {
					oos.writeObject(msg.obj);
					oos.flush();
					//在这里不仅需要向服务器发送指令 还需要给自己的UI线程发送指令
					Message msg2=new Message();
					msg2.what=0x123;
					msg2.obj=msg.obj;
					handler.sendMessage(msg2);
					System.out.println("Send Message to UI handler!");
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		};
		Looper.loop();

	}

}
